<?php

namespace App\Repositories;

use App\Exceptions\BasicException;
use App\Models\MainDB\Badge;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ContentRepository {


    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addAbout($param) {
        $addConfig = app('model_about')->create($param);

        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delAbout($idArr = []) {
        $res = app('model_about')->whereIn("id", $idArr)->delete();

        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveAbout($where,$param) {
        $saveConfig = app('model_about')->where($where)->update($param);

        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getAboutQueryList(Array $params) {
        $whereArr = [];
        if (!empty($params["status"])) {
            $whereArr["status"] = $params["status"];
        }

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('name', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_about')
            ->with("about_classify")
            ->where($whereArr)->where($whereFunc)->orderBy('id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = date("Y-m-d H:i:s", $item->add_time);
        }

        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addAboutClassify($param) {
        $addConfig = app('model_about_classify')->create($param);

        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delAboutClassify($idArr = []) {
        foreach ($idArr as $id) {
            $exist = app('model_about')->where('classify_id', $id)->value('id');
            if ($exist) throw new BasicException(0, "分类下还有文章，无法删除");
        }
        $res = app('model_about_classify')->whereIn("id", $idArr)->delete();

        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveAboutClassify($where,$param) {
        $saveConfig = app('model_about_classify')->where($where)->update($param);

        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getAboutClassifyQueryList(Array $params) {
        $whereArr = [];
        if (!empty($params["status"])) {
            $whereArr["status"] = $params["status"];
        }

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('name', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_about_classify')
            ->where($whereArr)->where($whereFunc)->orderBy('id','desc')->paginate($perPage, ['*'], '', $page);


        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addAd($param) {
        $addConfig = app('model_banner')->create($param);

        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delAd($idArr = []) {
        $res = app('model_banner')->whereIn("id", $idArr)->delete();

        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveAd($where,$param) {
        $saveConfig = app('model_banner')->where($where)->update($param);

        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getAdQueryList(Array $params) {
        $whereArr = [];
        if (isset($params["display"])) {
            $whereArr["t1.display"] = $params["display"];
        }

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('t1.title', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $bannerModel = app('model_banner');
        $bannerCategoryModel = app('model_banner_category');
        $result = $bannerModel
            ->from($bannerModel->getTable() . " as t1")
            ->selectRaw('t1.*,t2.title as category_name')
            ->leftJoin(DB::raw($bannerCategoryModel->getTable() . " as t2"), "t1.category_id", "=", "t2.id")
            ->where($whereArr)->where($whereFunc)->orderBy('t1.id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = date("Y-m-d H:i:s", $item->add_time);
            $item->start_time = date("Y-m-d H:i:s", $item->start_time);
            $item->end_time = date("Y-m-d H:i:s", $item->end_time);
            $item->category_name = $item->category_name??'无';
            $item->category_id = $item->category_id == 0 ? -1 : $item->category_id;
        }

        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addArticleCategory($param) {
        $addConfig = app('model_article_category')->create($param);
        Redis::del('article:cat');
        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delArticleCategory($idArr = []) {
        $res = app('model_article_category')->whereIn("article_cat_id", $idArr)->delete();
        Redis::del('article:cat');
        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveArticleCategory($where,$param) {
        $saveConfig = app('model_article_category')->where($where)->update($param);
        Redis::del('article:cat');
        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getArticleCategoryQueryList(Array $params) {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('cat_name', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_article_category')
            ->where($whereArr)->where($whereFunc)->orderBy('article_cat_id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = date("Y-m-d H:i:s", $item->add_time);
        }

        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addArticle($param) {
        $param['addtime'] = time();
        $addConfig = app('model_article')->create($param);

        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delArticle($idArr = []) {
        $res = app('model_article')->whereIn("article_id", $idArr)->delete();

        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveArticle($where,$param) {
        $saveConfig = app('model_article')->where($where)->update($param);

        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getArticleQueryList(Array $params) {
        $whereArr = [];
        if (isset($params['article_cat_id'])) {
            $whereArr[] = ["article_cat_id", "=", $params['article_cat_id']];
        }
        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('title', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_article')
            ->where($whereArr)->where($whereFunc)->orderBy('article_id','desc')->paginate($perPage, ['*'], '', $page);

        foreach ($result as $item) {
            $item->add_time = date("Y-m-d H:i:s", $item->addtime);
        }

        return $result;
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getChatLogQueryList(Array $params) {
        $whereArr = [];
        $whereArr[] = ['type', '=', $params['type']];
        if (!empty($params['date_start'])) {
            $whereArr[] = ['add_time', '>=', strtotime($params["date_start"] . ' 0:0:0')];
        }
        if (!empty($params['date_end'])) {
            $whereArr[] = ['add_time', '<=', strtotime($params['date_end'] . ' 23:59:59')];
        }
        if (!empty($params['content'])) {
            $whereArr[] = ['content', '=', $params['content']];
        }
        if (!empty($params['user_code'])) {
            $userId = app('model_user_data')->where('user_code', $params['user_code'])->value('user_id');
            if ($userId) {
                $whereArr[] = ['user_id', '=', $userId];
            } else {
                $whereArr[] = ['user_id', '=', -1];
            }
        }
        if (!empty($params['nickname'])) {
            $userId = app('model_user_data')->where('nickname', $params['nickname'])->value('user_id');
            if ($userId) {
                $whereArr[] = ['user_id', '=', $userId];
            } else {
                $whereArr[] = ['user_id', '=', -1];
            }
        }

        if ($params['type'] == 1) { //群聊
            if (!empty($params['room_name'])) {
                $rmId = app('model_user_room')->where('room_name', $params['room_name'])->value('id');
                if ($rmId) {
                    $whereArr[] = ['room_id', '=', $rmId];
                } else {
                    $whereArr[] = ['room_id', '=', -1];
                }
            }
        } else { //私聊
            if (!empty($params['target_user_code'])) {
                $userId = app('model_user_data')->where('user_code', $params['target_user_code'])->value('user_id');
                if ($userId) {
                    $whereArr[] = ['user_id_to', '=', $userId];
                } else {
                    $whereArr[] = ['user_id_to', '=', -1];
                }
            }
            if (!empty($params['target_nickname'])) {
                $userId = app('model_user_data')->where('nickname', $params['target_nickname'])->value('user_id');
                if ($userId) {
                    $whereArr[] = ['user_id_to', '=', $userId];
                } else {
                    $whereArr[] = ['user_id_to', '=', -1];
                }
            }
        }
        $sociaty = app('model_sc_sociaty_user');
        $data = app('model_chat')
            ->selectRaw('user_id,user_id_to,room_id,content,type,add_time')
            ->where($whereArr);

        if (isset($params['user_type'])){
            if ($params['user_type'] == 0){
                $sociatyUser = $sociaty->select('type', 'user_id')->get()->toArray();
                if (!empty($sociatyUser)){
                    $userIds = array_column($sociatyUser, 'user_id');
                } else {
                    $userIds = [];
                }
                $data = $data->whereNotIn('user_id', $userIds);
            } else {
                $userIds = $sociaty->where('type', $params['user_type'])->pluck('user_id')->toArray();
                $data = $data->whereIn('user_id', $userIds);
            }
        }

        if (isset($params['user_to_type'])){
            if ($params['user_to_type'] == 0){
                if (!isset($sociatyUser)){
                    $sociatyUser = $sociaty->select('type', 'user_id')->get()->toArray();
                }
                if (!empty($sociatyUser)){
                    $userIds = array_column($sociatyUser, 'user_id');
                } else {
                    $userIds = [];
                }
                $data = $data->whereNotIn('user_id_to', $userIds);
            } else {
                $userIds = $sociaty->where('type', $params['user_to_type'])->pluck('user_id')->toArray();
                $data = $data->whereIn('user_id_to', $userIds);
            }
        }

        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $data = $data->orderBy('id', 'desc')
            ->paginate($perPage)->toArray();

        //获取用户数据
        $userIds = array_column($data['data'], 'user_id', 'user_id');
        if ($params['type'] == 2) {
            $targetUserIds = array_column($data['data'], 'user_id_to', 'user_id_to');
            $userIds = array_merge($userIds, $targetUserIds);
        }
        $userDatas = app('model_user_data')
            ->select('user_id', 'user_code', 'head_picture', 'nickname')
            ->whereIn('user_id', $userIds)->get()->toArray();
        $userDatas = array_column($userDatas, null, 'user_id');

        //获取房间信息
        if ($params['type'] == 1) {
            $rmIds = array_column($data['data'], 'room_id', 'room_id');
            $rooms = app('model_user_room')->whereIn('id', $rmIds)->pluck('room_name', 'id')->toArray();
        }
        //获取用户类型
        if (!isset($sociatyUser)){
            $sociatyUser = $sociaty->select('type', 'user_id')->get()->toArray();
        }
        $userTypes = array_column($sociatyUser, 'type', 'user_id');

        foreach ($data['data'] as &$v) {
            $v['chat_time'] = date("Y-m-d H:i:s", $v['add_time']);
            if ($params['type'] == 1) {
                if (isset($rooms[$v['room_id']])) {
                    $v['room_name'] = $rooms[$v['room_id']];
                }
            } else {
                if (isset($userDatas[$v['user_id_to']])) {
                    $v['target_user_code'] = $userDatas[$v['user_id_to']]['user_code'];
                    $v['target_nickname'] = $userDatas[$v['user_id_to']]['nickname'];
                    $v['target_head_picture'] = $userDatas[$v['user_id_to']]['head_picture'];
                }
            }
            if (isset($userDatas[$v['user_id']])) {
                $v['user_code'] = $userDatas[$v['user_id']]['user_code'];
                $v['nickname'] = $userDatas[$v['user_id']]['nickname'];
                $v['head_picture'] = $userDatas[$v['user_id']]['head_picture'];
            }
            $v['user_type'] = !isset($userTypes[$v['user_id']]) ? 0 : $userTypes[$v['user_id']];
            $v['user_to_type'] = !isset($userTypes[$v['user_id_to']]) ? 0 : $userTypes[$v['user_id_to']];
        }

        return $data;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addFace($param) {
        $addConfig = app('model_face')->create($param);
        Redis::del("face:list");
        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delFace($idArr = []) {
        $res = app('model_face')->whereIn("id", $idArr)->delete();
        Redis::del("face:list");
        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveFace($where,$param) {
        $saveConfig = app('model_face')->where($where)->update($param);
        Redis::del("face:list");
        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getFaceQueryList(Array $params) {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('name', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_face')
            ->where($whereArr)->where($whereFunc)->orderBy('sort','desc')->paginate($perPage, ['*'], '', $page);

        return $result;
    }

    /**
     * 新增
     * @param $param
     * @return bool
     * @throws BasicException
     */
    public function addFaceSpecial($param) {
        $addConfig = app('model_face_special')->create($param);
        Redis::del("face:list:special");
        if ($addConfig) return $addConfig;
        throw new BasicException(93045);
    }

    /**
     * 删除
     */
    public function delFaceSpecial($idArr = []) {
        $res = app('model_face_special')->whereIn("id", $idArr)->delete();
        Redis::del("face:list:special");
        if ($res) return $res;
        throw new BasicException(93044);
    }

    /**
     * 修改
     */
    public function saveFaceSpecial($where,$param) {
        $saveConfig = app('model_face_special')->where($where)->update($param);
        Redis::del("face:list:special");
        if ($saveConfig!==false) return true;
        throw new BasicException(93047);
    }

    /**
     * 管理员后台查询配置数据
     */
    public function getFaceSpecialQueryList(Array $params) {
        $whereArr = [];

        $whereFunc = function ($query) use ($params) {
            if (!empty($params["keyword"])) {
                $query->where('name', 'like', "%" . $params['keyword'] . "%");
            }
        };

        $page = empty($params['page']) ? 1 : $params['page'];
        $perPage = empty($params['perPage']) ? 10 : $params['perPage'];

        $result = app('model_face_special')
            ->with("nobility:id,name")
            ->where($whereArr)->where($whereFunc)->orderBy('id','desc')->paginate($perPage, ['*'], '', $page);


        return $result;
    }

}
